const express = require('express')
const router = express.Router()
const axios = require('axios')

// GLM-4-Flash API 配置
const GLM_API_CONFIG = {
  baseURL: 'https://open.bigmodel.cn/api/paas/v4/chat/completions',
  apiKey: '1ff43c86b89c456fb79bc5875a100599.npKT7EHd7EZXimQZ',
}

// 创建一个用于处理 GLM-4-Flash 请求的函数
async function chatWithGLM4Flash(messages) {
  try {
    const response = await axios.post(
      GLM_API_CONFIG.baseURL,
      {
        model: 'glm-4-flash', // 使用免费的 GLM-4-Flash 模型
        messages,
        temperature: 0.7,
        top_p: 0.9,
        request_id: Date.now().toString(), // 生成唯一请求ID
      },
      {
        headers: {
          'Content-Type': 'application/json',
          Authorization: `Bearer ${GLM_API_CONFIG.apiKey}`,
        },
      }
    )
    return response.data
  } catch (error) {
    console.error('GLM-4-Flash API 调用失败:', error)
    throw error
  }
}

// 创建聊天接口
router.post('/chat', async (req, res) => {
  try {
    const { message } = req.body

    if (!message) {
      return res.status(400).json({
        data: null,
        message: '缺少必要参数',
        code: 400,
      })
    }

    // 构建消息格式
    const messages = [
      {
        role: 'user',
        content: message,
      },
    ]

    // 调用 GLM-4-Flash API
    const response = await chatWithGLM4Flash(messages)

    res.json({
      data: response,
      message: '请求成功',
      code: 200,
    })
  } catch (error) {
    res.status(500).json({
      data: null,
      message: error.message,
      code: 500,
    })
  }
})

module.exports = router
